package io.renren.modules.sys.service.impl;

import io.renren.common.exception.RRException;
import io.renren.common.utils.Query;
import io.renren.common.utils.Validation;
import io.renren.modules.sys.dao.OrderItemDao;
import io.renren.modules.sys.dao.ProductDao;
import io.renren.modules.sys.dao.PurchaseDao;
import io.renren.modules.sys.entity.*;
import io.renren.modules.sys.searcher.OrderSearcher;
import io.renren.modules.sys.service.PurchaseService;
import io.renren.modules.sys.service.SysUserService;
import io.renren.modules.sys.vo.OrderItemDetailVO;
import io.renren.modules.sys.vo.OrderItemVO;
import io.renren.modules.sys.vo.OrderVO;
import io.renren.modules.sys.vo.OrdersDownVO;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.plugins.Page;
import io.renren.common.utils.PageUtils;

import io.renren.modules.sys.dao.OrdersDao;
import io.renren.modules.sys.service.OrdersService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;


@Service("ordersService")
public class OrdersServiceImpl implements OrdersService {

    @Autowired
    private OrdersDao ordersDao;

    @Autowired
    private OrderItemDao orderItemDao;

    @Autowired
    private ProductDao productDao;

    @Autowired
    private PurchaseDao purchaseDao;

    @Autowired
    private SysUserService sysUserService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        Page<OrderVO> page = new Query<OrderVO>(params).getPage();
        page.setRecords(ordersDao.selectList(page , params));
        return new PageUtils(page);
    }

    @Override
    @Transactional
    public OrdersEntity inserOrders(OrderVO orderVO) {

        Boolean isSuccess = true;
        BigDecimal totalPrice = new BigDecimal(0);
        SysUserEntity user = null;

        if(StringUtils.isEmpty(orderVO.getUserId())){
            user = (SysUserEntity)SecurityUtils.getSubject().getPrincipal();
        }else{
            user = sysUserService.selectById(orderVO.getUserId());
        }

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String time = simpleDateFormat.format(new Date());

        SimpleDateFormat simpleDateFormats = new SimpleDateFormat("yyyy");
        String queryTime  = simpleDateFormats.format(new Date());
        int count = ordersDao.selectCountOrder(queryTime);
        String number = "";
        if(count == 0){
            number = "0001";
        }
        if(count < 10){
            number = "000" + count;
        }
        if(count >= 10 && count < 100){
            number = "00" + count;
        }
        if(count >= 100 && count < 1000){
            number = "0" + count;
        }

        /**订单号生成方式 ZC-年月日-0000*/
        String orderCode = "ZC_" + time + "_" + number;

        /**订单总金额校验**/
        if(orderVO.getTotalPrice() == null){
            throw new RRException("订单总金额不对！！！");
        }

        /**订单详情校验*/
        if(CollectionUtils.isEmpty(orderVO.getOrderItems())){
            throw new RRException("没有订单列！！！");
        }

        for (OrderItemVO orderItemVO : orderVO.getOrderItems()){
            if(orderItemVO.getId() == null){
                throw new RRException("产品信息未传入 请联系开发人员！！！");
            }

            if(orderItemVO.getSupplierId() == null){
                throw new RRException("供应商信息未传入 请联系开发人员！！！");
            }

            if(orderItemVO.getId() == null){
                throw new RRException("产品信息未传入 请联系开发人员！！！");
            }
            if(!Validation.isINTEGER_NEGATIVE(orderItemVO.getNumBuyer().toString())){
                throw new RRException("供应商："+orderItemVO.getSupplierName()+" 产品名："+orderItemVO.getName()+" 购买数量不能为空且为正整数！！！");
            }

            if(!Validation.isMoney(orderItemVO.getPrice().toString())){
                throw new RRException("供应商："+orderItemVO.getSupplierName()+" 产品名："+orderItemVO.getName()+" 购买单价有误！！！");
            }

            if(!Validation.isMoney(orderItemVO.getTotalPrice().toString())){
                throw new RRException("供应商："+orderItemVO.getSupplierName()+" 产品名："+orderItemVO.getName()+" 购买总价有误！！！");
            }

            BigDecimal num = new BigDecimal(orderItemVO.getNumBuyer());
            BigDecimal orderItemTotalPrice = num.multiply(orderItemVO.getPrice());

            if(orderItemTotalPrice.compareTo(orderItemVO.getTotalPrice()) != 0){
                throw new RRException("供应商："+orderItemVO.getSupplierName()+" 产品名："+orderItemVO.getName()+" 计算有误，请注意网页攻击！！！");
            }

            totalPrice = totalPrice.add(orderItemTotalPrice);

        }

        if(totalPrice.compareTo(orderVO.getTotalPrice()) != 0){
            throw new RRException("总金额 计算有误，请注意网页攻击！！！");
        }

        /**保存订单*/
        OrdersEntity ordersEntity = new OrdersEntity();
        ordersEntity.setShopId(orderVO.getShopId());
        ordersEntity.setLogisticsFee(orderVO.getLogisticsFee());
        ordersEntity.setOrderNum(orderCode);
        ordersEntity.setType(orderVO.getType());
        ordersEntity.setTotalPrice(totalPrice);
        ordersEntity.setUserId(user.getUserId());
        ordersEntity.setRemark(orderVO.getRemark());
        int i = ordersDao.insertOrder(ordersEntity);

        if (i == 0){
            throw new RRException("出货单 保存失败！！！");
        }

        /**保存订单详情*/
        for (OrderItemVO orderItemVO : orderVO.getOrderItems()){
            /**获取商品信息*/
            ProductEntity product = productDao.selectById(orderItemVO.getId());

            OrderItemEntity orderItemEntity = new OrderItemEntity();
            orderItemEntity.setOrderId(ordersEntity.getId());
            orderItemEntity.setShopId(orderItemVO.getSupplierId());
            orderItemEntity.setShopName(orderItemVO.getSupplierName());
            orderItemEntity.setUserId(user.getUserId());
            orderItemEntity.setUserName(user.getUsername());
            orderItemEntity.setProductId(product.getId());
            orderItemEntity.setProductName(product.getName());
            orderItemEntity.setUnit(product.getUnit());

            PurchaseEntity purchase = purchaseDao.findLatelyByProductId(product.getId());
            if(purchase == null){
                throw  new RRException("未查到产品："+product.getName()+"的最近进价");
            }
            orderItemEntity.setCostPrice(purchase.getPrice());
            orderItemEntity.setSuggestPrice(purchase.getSuggestPrice());
            orderItemEntity.setInvoiceName(product.getInvoiceName());
            orderItemEntity.setPrice(orderItemVO.getPrice());
            orderItemEntity.setNumber(orderItemVO.getNumBuyer());
            int orderItemCount = orderItemDao.insert(orderItemEntity);
            if(orderItemCount > 0){
                /**减库存*/
                Integer newNum = product.getNumber() - orderItemVO.getNumBuyer();
                product.setNumber(newNum);
                orderItemCount = productDao.updateById(product);
                if(orderItemCount == 0){
                    throw  new RRException("库存修改失败！！！");
                }
            }
        }
        return ordersEntity;
    }

    @Override
    public List<OrdersDownVO> selectOrderListDown(OrderSearcher searcher) {
        return ordersDao.selectOrderListDown(searcher);
    }

    @Override
    public OrdersEntity findOrderById(Long id) {
        return ordersDao.selectById(id);
    }

    @Override
    public Boolean updateOrder(OrdersEntity order) {
        int i = ordersDao.updateAllColumnById(order);
        if(i > 0){
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    @Override
    public OrderVO selectOrderInfoList(Long orderId) {
        return ordersDao.selectOrderInfoList(orderId);
    }

}
